package com.xiaohao.communication.daoImpl;

import com.xiaohao.communication.bean.GoldCoin;
import com.xiaohao.communication.dao.UserGoldCoinDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserGoldCoinDaoImpl implements UserGoldCoinDao {


    @Autowired
    MongoTemplate mongoTemplate;

    /*
    * 查询金币
    * */
    @Override
    public List<GoldCoin> getUserGoldCoin(int id) {

        List<GoldCoin> goldCoins = mongoTemplate.find(new Query(Criteria.where("user_id").is(id)), GoldCoin.class, "goldcoin");
        return goldCoins;
    }

    /*
     * 增加将金币
     * */
    @Override
    public void addUserGoldCoin(GoldCoin goldCoin) {

        int user_id = goldCoin.getUser_id();
        int addGoldCoinNumber = goldCoin.getGoldCoinNumber();

        //获取数据库的金币数
        Query query = new Query(Criteria.where("user_id").is(user_id));
        List<GoldCoin> goldcoin = mongoTemplate.find(query, GoldCoin.class, "goldcoin");
        GoldCoin goldCoin1 = goldcoin.get(0);
        int oldGoldCoinNumber = goldCoin1.getGoldCoinNumber();

        //更新数据库金币
        Update update = new Update();
        update.set("goldCoinNumber",oldGoldCoinNumber+addGoldCoinNumber);
        mongoTemplate.updateFirst(query,update,GoldCoin.class,"goldcoin");

    }

    /*
     * 减少金币
     * */
    @Override
    public void reduceUserGoldCoin(GoldCoin goldCoin) {
        int user_id = goldCoin.getUser_id();
        int reduceGoldCoinNumber = goldCoin.getGoldCoinNumber();   //要减的金币数

        //获取数据库中的金币。
        Query query = new Query(Criteria.where("user_id").is(user_id));
        List<GoldCoin> goldcoin = mongoTemplate.find(query, GoldCoin.class, "goldcoin");
        GoldCoin goldCoin1 = goldcoin.get(0);
        int oldGoldCoinNumber = goldCoin1.getGoldCoinNumber();

        //更新数据库金币
        Update update = new Update();
        update.set("goldCoinNumber",oldGoldCoinNumber-reduceGoldCoinNumber);
        mongoTemplate.updateFirst(query, update, GoldCoin.class,"goldcoin");
    }
}
